import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    
    // 添加token
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }

    // 添加请求时间戳（防止缓存）
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    // 显示loading
    if (config.loading !== false) {
      // 可以在这里显示全局loading
    }

    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { data, config } = response
    
    // 隐藏loading
    if (config.loading !== false) {
      // 可以在这里隐藏全局loading
    }

    // 处理blob类型响应（文件下载）
    if (response.config.responseType === 'blob') {
      return response
    }

    // 检查业务状态码
    if (data.code !== undefined) {
      if (data.code === 200 || data.code === 0) {
        return data.data || data
      } else if (data.code === 401) {
        // 未授权，跳转登录页
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
        return Promise.reject(new Error(data.message || '登录已过期'))
      } else {
        // 其他业务错误
        const errorMessage = data.message || '请求失败'
        if (config.showError !== false) {
          ElMessage.error(errorMessage)
        }
        return Promise.reject(new Error(errorMessage))
      }
    }

    return data
  },
  error => {
    // 隐藏loading
    if (error.config?.loading !== false) {
      // 可以在这里隐藏全局loading
    }

    let errorMessage = '网络错误'
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          errorMessage = data?.message || '请求参数错误'
          break
        case 401:
          errorMessage = '未授权，请重新登录'
          const userStore = useUserStore()
          userStore.logout()
          router.push('/login')
          break
        case 403:
          errorMessage = '拒绝访问'
          break
        case 404:
          errorMessage = '请求地址不存在'
          break
        case 408:
          errorMessage = '请求超时'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        case 501:
          errorMessage = '服务未实现'
          break
        case 502:
          errorMessage = '网关错误'
          break
        case 503:
          errorMessage = '服务不可用'
          break
        case 504:
          errorMessage = '网关超时'
          break
        default:
          errorMessage = data?.message || `连接错误${status}`
      }
    } else if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时'
    } else if (error.message.includes('Network Error')) {
      errorMessage = '网络连接异常'
    }

    if (error.config?.showError !== false) {
      ElMessage.error(errorMessage)
    }

    console.error('Response error:', error)
    return Promise.reject(error)
  }
)

// 导出请求方法
export default service

// 常用请求方法封装
export const request = {
  get(url, params, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      ...config
    })
  },
  
  post(url, data, config = {}) {
    return service({
      method: 'post',
      url,
      data,
      ...config
    })
  },
  
  put(url, data, config = {}) {
    return service({
      method: 'put',
      url,
      data,
      ...config
    })
  },
  
  delete(url, config = {}) {
    return service({
      method: 'delete',
      url,
      ...config
    })
  },
  
  patch(url, data, config = {}) {
    return service({
      method: 'patch',
      url,
      data,
      ...config
    })
  },
  
  upload(url, formData, config = {}) {
    return service({
      method: 'post',
      url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    })
  },
  
  download(url, params, config = {}) {
    return service({
      method: 'get',
      url,
      params,
      responseType: 'blob',
      ...config
    })
  }
}
